import 'dart:async';

import 'package:changxindianzishangwu/cache/local_cache.dart';
import 'package:changxindianzishangwu/dao/login_init_dao.dart';
import 'package:changxindianzishangwu/dao/sms_code_dao.dart';
import 'package:changxindianzishangwu/db/ec_cache.dart';
import 'package:changxindianzishangwu/model/user_info_model.dart';
import 'package:changxindianzishangwu/provider/user.dart';
import 'package:changxindianzishangwu/util/colors.dart';
import 'package:changxindianzishangwu/util/universal_view.dart';
import 'package:changxindianzishangwu/widget/app_bar.dart';
import 'package:changxindianzishangwu/util/toast.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:provider/provider.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_user_full_info.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_value_callback.dart';
import 'package:tencent_im_sdk_plugin/tencent_im_sdk_plugin.dart';
import 'package:tpns_flutter_plugin/tpns_flutter_plugin.dart';

import 'login_update_info_page.dart';

class GetMessagePage extends StatefulWidget {
  GetMessagePage({Key key}) : super(key: key);

  @override
  _GetMessagePageState createState() => _GetMessagePageState();
}

class _GetMessagePageState extends State<GetMessagePage> {
  var phone = Get.arguments["telephone"];
  var areaCode = Get.arguments["areaCode"];
  var codeFlag = Get.arguments["flag"];

  Timer _timer;

  //主要为了防止重复点击
  bool flag = false;
  var message;

  @override
  void initState() {
    super.initState();
    _startTimer(60);
  }

  @override
  void dispose() {
    super.dispose();
    _timer.cancel();
  }

  var result;

  _loginMessage()async {

    //短信验证
    var _userinfoModel =await LoginInitDao.msmRegister(
        phone, areaCode, message);
    if (_userinfoModel is int) {
      toast("登录/注册失败");
      return;
    }
    TencentImSDKPlugin.v2TIMManager
        .login(
      userID: _userinfoModel.data.userId,
      userSig: _userinfoModel.data.userSig,
    )
        .then((res) async {
      if (res.code == 0) {
        getData();
        final XgFlutterPlugin tpush = new XgFlutterPlugin();
        tpush.setAccount(getUserId(), AccountType.UNKNOWN);
        showToast("登录成功");
        return _userinfoModel.data.isFirstIn == 1
            ? Get.offAllNamed(
          "/homePage",
          arguments: getAppLoginToken(),
        )
            : Get.offAll(LoginUpdateInfoPage());
      }
    });

  }
  getData() async {
    V2TimValueCallback<List<V2TimUserFullInfo>> infos = await TencentImSDKPlugin
        .v2TIMManager
        .getUsersInfo(userIDList: [EcCache.getInstance().get('userId')]);
    if (infos.code == 0) {
      Provider.of<UserModel>(context, listen: false).setInfo(infos.data[0]);
    }
  }
  var _autoCodeText = "60s 重新获取";

  void _startTimer(num) {
    flag = false;
    int _timeCount = num;
    showToast("短信验证码已发送，请注意查收");
    _timer = Timer.periodic(
        Duration(seconds: 1),
            (Timer timer) =>
        {
          setState(() {
            if (_timeCount <= 0) {
              _autoCodeText = '重新发送验证码';
              _timer.cancel();
              flag = true;
            } else {
              _timeCount -= 1;
              _autoCodeText = " $_timeCount" + 's 重新获取';
            }
          })
        });
  }

  void stopTimer() {
    _timer.cancel();
  }

  _getSMS(codeFlags) async {
    if (codeFlags) {
      await SmsCodeDao.getCode(
          Get.arguments["telephone"], Get.arguments["areaCode"], SIMPLE);
    } else {
      await SmsCodeDao.getCode(
          Get.arguments["telephone"], Get.arguments["areaCode"], REGIS);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: TopAppBar(context, "登录/注册"),
      resizeToAvoidBottomInset: flag,
      body: GestureDetector(
        onTap: () {
          //收起键盘
          FocusScope.of(context).requestFocus(FocusNode());
        },
        child: Container(
          padding: EdgeInsets.only(left: width(13), right: width(13)),
          color: Colors.white,
          child: ListView(
            children: <Widget>[
              Container(
                height: ScreenUtil().setHeight(25),
                width: ScreenUtil().setWidth(120),
                margin: EdgeInsets.only(
                    top: ScreenUtil().setHeight(45),
                    right: ScreenUtil().setWidth(375 - 16 - 120)),
                child: Text(
                  "验证码已发送",
                  style: TextStyle(
                    fontSize: ScreenUtil().setSp(18),
                    fontFamily: "PingFang SC",
                    color: Color.fromRGBO(51, 51, 51, 1),
                  ),
                ),
              ),
              Container(
                height: ScreenUtil().setHeight(25),
                width: ScreenUtil().setWidth(219),
                margin: EdgeInsets.only(
                    right: ScreenUtil().setWidth(375 - 16 - 219),
                    top: ScreenUtil().setHeight(10)),
                child: Text(
                  "+${areaCode}  " + phone,
                  style: TextStyle(
                    fontSize: ScreenUtil().setSp(12),
                    fontFamily: "PingFang SC",
                    color: Color.fromRGBO(153, 153, 153, 1),
                  ),
                ),
              ),
              Container(
                height: ScreenUtil().setHeight(25),
                width: ScreenUtil().setWidth(219),
                margin: EdgeInsets.only(
                    right: ScreenUtil().setWidth(375 - 16 - 219),
                    top: ScreenUtil().setHeight(30)),
                child: Text(
                  "验证码",
                  style: TextStyle(
                    fontSize: ScreenUtil().setSp(13),
                    fontFamily: "PingFang SC",
                    color: Color.fromRGBO(85, 85, 85, 1),
                  ),
                ),
              ),
              Container(
                child: Row(
                  children: <Widget>[
                    Expanded(
                      flex: 2,
                      child: Container(
                        child: TextField(
                          onChanged: (text) {
                            print(text);
                            message = text;
                          },
                          keyboardType: TextInputType.number,
                          cursorColor: Colors.greenAccent,
                          decoration: InputDecoration(
                            border: InputBorder.none,
                            hintText: "请输入",
                            hintStyle: TextStyle(
                              fontSize: ScreenUtil().setSp(13),
                              color: Color.fromRGBO(153, 153, 153, 1),
                            ),
                          ),
                        ),
                      ),
                    ),
                    Expanded(
                      child: InkWell(
                        child: Text(_autoCodeText.toString()),
                        onTap: () {
                          if (flag) {
                            _startTimer(60);
                            _getSMS(codeFlag);
                          } else {
                            showToast("请稍等");
                          }

                          print("重新获取验证码");
                        },
                      ),
                    )
                  ],
                ),
              ),
              UniversalView().line(),
              InkWell(
                onTap: () {
                  FocusScope.of(context).requestFocus(FocusNode());

                  _loginMessage();
                  //stopTimer();
                  print("登录");
                },
                child: Container(
                  height: ScreenUtil().setHeight(44),
                  width: ScreenUtil().setWidth(300),
                  margin: EdgeInsets.only(
                      right: ScreenUtil().setWidth(75 / 2),
                      left: ScreenUtil().setWidth(75 / 2),
                      top: ScreenUtil().setHeight(60)),
                  alignment: Alignment.center,
                  decoration: BoxDecoration(
                      color: Color.fromRGBO(0, 220, 169, 1),
                      borderRadius:
                      BorderRadius.circular(ScreenUtil().radius(5))),
                  child: Text(
                    "登录",
                    style: TextStyle(
                        fontSize: ScreenUtil().setSp(15),
                        color: Colors.white,
                        fontFamily: "PingFang SC"),
                  ),
                ),
              ),
              InkWell(
                onTap: () {
                  print("收不到验证码");
                },
                child: Container(
                  alignment: Alignment.center,
                  height: ScreenUtil().setHeight(44),
                  width: ScreenUtil().setWidth(300),
                  margin: EdgeInsets.only(
                      right: ScreenUtil().setWidth(75 / 2),
                      left: ScreenUtil().setWidth(75 / 2),
                      top: ScreenUtil().setHeight(25)),
                  child: Text(
                    "收不到验证码？",
                    style: TextStyle(
                        fontSize: ScreenUtil().setSp(13),
                        color: Color.fromRGBO(153, 153, 153, 1),
                        fontFamily: "PingFang SC"),
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
